package com.tiger.admin.http.encipher;

import jakarta.servlet.http.HttpSession;
import org.springframework.stereotype.Service;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import java.nio.charset.StandardCharsets;
import java.security.*;
import java.security.spec.PKCS8EncodedKeySpec;
import java.util.Base64;

@Service
public class EncipherService {
    public final String pubKey = "epubKey";
    public final String priKey = "epriKey";

    private static KeyPair generateKeyPair() {
       try{
           KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
           keyPairGenerator.initialize(2048); // 可以设置密钥长度
           return keyPairGenerator.generateKeyPair();
       }catch (Exception e) {
        System.out.println(e.getMessage());
       }

       return null;
    }

    public String getPublic(HttpSession session) {
        Object key = session.getAttribute(pubKey);

        if (key == null) {
            KeyPair keyPair = generateKeyPair();
            if (keyPair != null) {
                String pubkeyString = Base64.getEncoder().encodeToString(keyPair.getPublic().getEncoded());//keyPair.getPublic().toString();System.out.println(pubkey);
                session.setAttribute(pubKey, pubkeyString);
                session.setAttribute(priKey, Base64.getEncoder().encodeToString(keyPair.getPrivate().getEncoded()));

                return pubkeyString;
            }
        }else {
            return (String) key;
        }

        return null;
    }

    public String decrypt(HttpSession session, String encryptedDataBase64)  {
        try {
            String privateKeyString = (String) session.getAttribute(priKey);
            byte[] privateKeyBytes = Base64.getDecoder().decode(privateKeyString);

            PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(privateKeyBytes);

            // 初始化KeyFactory
            KeyFactory keyFactory = KeyFactory.getInstance("RSA");

            // 将KeySpec转换为PrivateKey
            PrivateKey privateKey = keyFactory.generatePrivate(keySpec);

            byte[] encryptedData = Base64.getDecoder().decode(encryptedDataBase64);

            // 初始化Cipher进行解密
            Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding"); // 注意：填充模式可能需要根据实际情况调整
            cipher.init(Cipher.DECRYPT_MODE, privateKey);

            // 执行解密操作
            byte[] decryptedBytes = cipher.doFinal(encryptedData);

            return new String(decryptedBytes, StandardCharsets.UTF_8);

        } catch (Exception e) {
            System.out.println(e.getMessage());
        }

        return null;
    }

}
